<template>
	<view class="page-container">
		<!-- 顶部导航栏 -->
		<u-navbar bgColor="#FFFFFF" :placeholder="true" borderBottom>
			<view slot="left" class="navbar-left">
				<navigator url="/pageNew/pages/accounting/index" class="back-navigator">
					<u-icon color="#1e88e5" name="arrow-left"></u-icon>
					<text class="header-title">收入录入</text>
				</navigator>
			</view>
			<view slot="title" class="navbar-title">
				添加收入
			</view>
		</u-navbar>

		<!-- 主内容区 -->
		<view class="content-container">
			<view class="form-card">
				<!-- 银行导入按钮 - 独立区域避免重叠 -->
				<view class="card-header">
					<button class="bank-import-btn" @click="importFromBank">
						<u-icon name="rmb-circle" color="#1e88e5" size="18" class="import-icon"></u-icon>
						<text class="import-text">从银行导入</text>
					</button>
				</view>

				<form @submit="saveIncome">
					<!-- 收入类型 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">收入类型</text>
								<text class="required-star">*</text>
							</view>
							<picker class="picker-field" mode="selector" :range="incomeCategories" range-key="label"
								v-model="selectedCategory" @change="onCategoryChange">
								<view class="picker-display">
									{{ selectedCategory === -1 ? '请选择收入类型' : incomeCategories[selectedCategory].label }}
								</view>
							</picker>
						</view>
					</view>

					<!-- 金额 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">金额<u-icon name="rmb" color="#6b7280" size="16"
										class="currency-icon"></u-icon></text>
								<text class="required-star">*</text>
							</view>
							<view class="amount-input-wrapper">

								<input type="number" placeholder="请输入收入金额" class="amount-input" v-model="amount"
									@input="validateAmount">
							</view>
						</view>
					</view>

					<!-- 日期 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">日期</text>
								<text class="required-star">*</text>
							</view>
							<picker class="picker-field" mode="date" start="2010-01-01" end="2099-12-31"
								:value="selectedDate" @change="onDateChange">
								<view class="picker-display">
									{{ selectedDate || '请选择日期' }}
								</view>
							</picker>
						</view>
					</view>

					<!-- 银行流水号 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">银行流水号</text>
							</view>
							<input type="text" placeholder="请输入银行流水号" class="text-input" v-model="bankSerial">
						</view>
					</view>

					<!-- 发票上传（严格遵循u-upload文档规范） -->
					<view class="form-row upload-row">
						<view class="label-wrapper upload-label">
							<text class="field-label">发票</text>
						</view>
						<view class="upload-container">
							<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
								:multiple="false" :maxCount="1" accept="file" :previewFullImage="true"
								upload-text="点击上传发票" uploadIcon="file-text" uploadIconColor="#1e88e5" width="120"
								height="120"></u-upload>
						</view>
					</view>

					<!-- 附件上传（严格遵循u-upload文档规范） -->
					<view class="form-row upload-row">
						<view class="label-wrapper upload-label">
							<text class="field-label">附件</text>
						</view>
						<view class="upload-container">
							<u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2"
								:multiple="false" :maxCount="1" accept="file" :previewFullImage="true"
								upload-text="点击上传附件" uploadIcon="attach" uploadIconColor="#1e88e5" width="120"
								height="120"></u-upload>
						</view>
					</view>

					<!-- 备注 -->
					<view class="form-row">
						<view class="form-field textarea-field-wrapper">
							<view class="label-wrapper">
								<text class="field-label">备注</text>
							</view>
							<textarea placeholder="请输入备注信息" class="textarea-field" v-model="remarks"
								rows="3"></textarea>
						</view>
					</view>
				</form>
			</view>
		</view>

		<!-- 底部固定按钮区域 -->
		<view class="fixed-bottom-buttons">
			<navigator url="/pageNew/pages/accounting/index" class="btn cancel-btn">
				取消
			</navigator>
			<button class="btn save-btn" @click="saveIncome">
				保存
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 收入分类
				incomeCategories: [{
						value: 'salary',
						label: '工资收入'
					},
					{
						value: 'business',
						label: '经营收入'
					},
					{
						value: 'investment',
						label: '投资收益'
					},
					{
						value: 'other',
						label: '其他收入'
					}
				],
				selectedCategory: -1,

				// 金额
				amount: '',

				// 日期
				selectedDate: '',

				// 银行流水号
				bankSerial: '',

				// 上传文件列表（严格遵循u-upload文档格式）
				fileList1: [], // 发票文件列表（name="1"）
				fileList2: [], // 附件文件列表（name="2"）

				// 备注
				remarks: '',

				// 上传服务器地址（实际项目替换为真实接口）
				uploadUrl: "http://192.168.2.21:7001/upload"
			};
		},
		onLoad() {
			console.log('添加收入页面加载完成');
			// 默认选择今天
			const today = new Date();
			this.selectedDate = this.formatDate(today);
		},
		methods: {
			// 格式化日期
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 分类变更
			onCategoryChange(e) {
				this.selectedCategory = e.detail.value;
			},

			// 日期变更
			onDateChange(e) {
				this.selectedDate = e.detail.value;
			},

			// 验证金额
			validateAmount() {
				if (this.amount && parseFloat(this.amount) < 0) {
					this.amount = '';
					uni.showToast({
						title: '金额不能为负数',
						icon: 'none'
					});
				}
			},

			// 上传文件（严格遵循u-upload文档规范）
			async afterRead(event) {
				// 当multiple为false时，file为对象格式
				let lists = [].concat(event.file);
				let fileListKey = `fileList${event.name}`;
				let fileListLen = this[fileListKey].length;

				// 添加上传中状态的文件
				lists.map((item) => {
					this[fileListKey].push({
						...item,
						status: "uploading",
						message: "上传中",
						name: item.name // 保存文件名
					});
				});

				// 循环上传文件
				for (let i = 0; i < lists.length; i++) {
					try {
						const result = await this.uploadFilePromise(lists[i].url);
						// 更新文件状态为上传成功
						let item = this[fileListKey][fileListLen];
						this[fileListKey].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: "success",
								message: "",
								url: result, // 服务器返回的文件地址
								path: lists[i].path // 保留本地路径用于预览
							})
						);
						fileListLen++;
					} catch (error) {
						// 上传失败处理
						let item = this[fileListKey][fileListLen];
						this[fileListKey].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: "fail",
								message: "上传失败",
								url: lists[i].path
							})
						);
						fileListLen++;
						uni.showToast({
							title: '文件上传失败',
							icon: 'none'
						});
					}
				}
			},

			// 删除文件（严格遵循u-upload文档规范）
			deletePic(event) {
				const fileListKey = `fileList${event.name}`;
				this[fileListKey].splice(event.index, 1);
			},

			// 上传文件Promise（严格遵循u-upload文档示例）
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.uploadUrl, // 实际项目替换为真实接口地址
						filePath: url,
						name: "file",
						formData: {
							type: "accounting" // 自定义参数，根据需求调整
						},
						success: (res) => {
							setTimeout(() => {
								// 模拟上传成功，实际项目需解析res.data获取真实地址
								// 这里直接返回本地路径用于预览，实际应返回服务器地址
								resolve(url);
							}, 1000);
						},
						fail: (err) => {
							console.error('文件上传失败：', err);
							reject(err);
						}
					});
				});
			},

			// 从银行导入
			importFromBank() {
				uni.showToast({
					title: '打开银行导入功能',
					icon: 'none'
				});
				// 实际项目可添加：
				// 1. 银行API授权验证
				// 2. 获取银行交易记录
				// 3. 自动填充表单（金额、日期、流水号等）
			},

			// 保存收入
			saveIncome() {
				// 表单验证
				if (this.selectedCategory === -1) {
					uni.showToast({
						title: '请选择收入类型',
						icon: 'none'
					});
					return;
				}

				if (!this.amount || parseFloat(this.amount) <= 0) {
					uni.showToast({
						title: '请输入有效的收入金额',
						icon: 'none'
					});
					return;
				}

				if (!this.selectedDate) {
					uni.showToast({
						title: '请选择日期',
						icon: 'none'
					});
					return;
				}

				// 整理上传文件信息
				const invoiceFile = this.fileList1[0] || {};
				const attachmentFile = this.fileList2[0] || {};

				// 创建收入记录
				const incomeRecord = {
					id: Date.now().toString(), // 时间戳唯一ID
					type: 'income',
					category: this.incomeCategories[this.selectedCategory].value,
					categoryLabel: this.incomeCategories[this.selectedCategory].label,
					amount: parseFloat(this.amount),
					date: this.selectedDate,
					bankSerial: this.bankSerial || '',
					// 发票信息
					hasInvoice: this.fileList1.length > 0,
					invoiceFileName: invoiceFile.name || '',
					invoiceFileUrl: invoiceFile.url || '',
					invoiceFileStatus: invoiceFile.status || '',
					// 附件信息
					hasAttachment: this.fileList2.length > 0,
					attachmentFileName: attachmentFile.name || '',
					attachmentFileUrl: attachmentFile.url || '',
					attachmentFileStatus: attachmentFile.status || '',
					remarks: this.remarks || '',
					createdAt: new Date().toISOString()
				};

				// 保存到本地存储
				let accountingRecords = uni.getStorageSync('accountingRecords') || [];
				accountingRecords.push(incomeRecord);
				uni.setStorageSync('accountingRecords', accountingRecords);

				// 显示成功提示并返回
				uni.showToast({
					title: '收入添加成功',
					icon: 'success'
				});
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 1500);
			}
		}
	};
</script>
<style scoped>
	/* 全局容器样式 */
	.page-container {
		min-height: 100vh;
		background-color: #f9fafb;
		position: relative;
	}

	/* 导航栏样式 */
	.navbar-left {
		display: flex;
		align-items: center;
	}

	.back-navigator {
		display: flex;
		align-items: center;
		text-decoration: none;
	}

	.navbar-title {
		font-size: 16px;
		font-weight: 600;
		color: #1e88e5;
	}

	.header-title {
		font-size: 18px;
		font-weight: 600;
		color: #1e88e5;
		margin-left: 8px;
	}

	/* 内容容器样式 */
	.content-container {
		margin: 0 auto;
		padding: 16px;
		padding-bottom: 80px;
		box-sizing: border-box;
		max-width: 750rpx;
	}

	/* 表单卡片样式 */
	.form-card {
		background-color: #ffffff;
		border-radius: 12px;
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
		padding: 20px;
		position: relative;
	}

	/* 卡片头部 - 银行导入按钮区域 */
	.card-header {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 24px;
	}

	/* 银行导入按钮样式 */
	.bank-import-btn {
		display: flex;
		align-items: center;
		background: linear-gradient(135deg, #e6f7ff 0%, #d1efff 100%);
		border: none;
		border-radius: 28px;
		margin: 0;
		font-size: 14px;
		transition: all 0.3s ease;
	}

	.bank-import-btn:active {
		background: linear-gradient(135deg, #d1efff 0%, #b8e2ff 100%);
		transform: scale(0.98);
	}

	.import-icon {
		margin-right: 8px;
	}

	.import-text {
		color: #1e88e5;
		font-weight: 500;
	}

	/* 表单行样式 */
	.form-row {
		margin-bottom: 20px;
		padding: 4px 0;
	}

	.form-field {
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 100%;
	}

	/* 上传行特殊样式 */
	.upload-row {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		margin-bottom: 24px;
	}

	/* 标签容器 */
	.label-wrapper {
		width: 100px;
		flex-shrink: 0;
		display: flex;
		align-items: center;
		padding-right: 12px;
		box-sizing: border-box;
	}

	/* 上传标签样式 */
	.upload-label {
		align-items: flex-start;
		padding-top: 12px;
	}

	/* 字段标签样式 */
	.field-label {
		font-size: 14px;
		color: #6b7280;
	}

	.required-star {
		color: #f44336;
		margin-left: 4px;
	}

	/* 选择器样式 */
	.picker-field {
		flex-grow: 1;
	}

	.picker-display {
		width: 100%;
		height: 44px;
		line-height: 44px;
		padding: 0 16px;
		border: 1px solid #e5e7eb;
		border-radius: 8px;
		font-size: 14px;
		color: #1f2937;
		box-sizing: border-box;
	}

	/* 金额输入框样式 */
	.amount-input-wrapper {
		flex-grow: 1;
		position: relative;
	}

	.currency-icon {
		position: absolute;
		left: 16px;
		top: 50%;
		transform: translateY(-50%);
	}

	.amount-input {
		width: 100%;
		height: 44px;
		padding: 0 16px 0 36px;
		border: 1px solid #e5e7eb;
		border-radius: 8px;
		font-size: 14px;
		color: #1f2937;
		box-sizing: border-box;
	}

	.amount-input::placeholder {
		color: #9ca3af;
		opacity: 1;
	}

	/* 文本输入框样式 */
	.text-input {
		flex-grow: 1;
		height: 44px;
		padding: 0 16px;
		border: 1px solid #e5e7eb;
		border-radius: 8px;
		font-size: 14px;
		color: #1f2937;
		box-sizing: border-box;
	}

	.text-input::placeholder {
		color: #9ca3af;
		opacity: 1;
	}

	/* 上传容器样式 */
	.upload-container {
		flex-grow: 1;
	}

	/* 文本域样式 */
	.textarea-field-wrapper {
		align-items: flex-start;
		padding-top: 8px;
	}

	.textarea-field {
		flex-grow: 1;
		min-height: 80px;
		padding: 12px 16px;
		border: 1px solid #e5e7eb;
		border-radius: 8px;
		font-size: 14px;
		color: #1f2937;
		resize: vertical;
		box-sizing: border-box;
	}

	.textarea-field::placeholder {
		color: #9ca3af;
		opacity: 1;
	}

	/* 底部固定按钮区域 */
	.fixed-bottom-buttons {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		padding: 12px 16px;
		box-sizing: border-box;
		display: flex;
		gap: 12px;
		max-width: 750rpx;
		margin: 0 auto;
	}

	/* 按钮通用样式 */
	.btn {
		flex: 1;
		height: 44px;
		line-height: 44px;
		text-align: center;
		border-radius: 8px;
		font-size: 15px;
		font-weight: 500;
		transition: all 0.2s ease;
	}

	/* 取消按钮样式 */
	.cancel-btn {
		background-color: #f3f4f6;
		color: #4b5563;
		text-decoration: none;
	}

	.cancel-btn:active {
		background-color: #e5e7eb;
	}

	/* 保存按钮样式 */
	.save-btn {
		background-color: #1e88e5;
		color: #ffffff;
		border: none;
	}

	.save-btn:active {
		background-color: #1976d2;
	}

	/* u-upload 组件样式补充 */
	::v-deep .u-upload__upload-btn {
		border-radius: 8px !important;
		background-color: #f9fafb !important;
		border: 1px dashed #d1d5db !important;
	}

	::v-deep .u-upload__upload-text {
		color: #6b7280 !important;
		font-size: 14px !important;
		margin-top: 8px !important;
	}

	::v-deep .u-upload__file {
		border-radius: 8px !important;
		overflow: hidden !important;
	}

	::v-deep .u-upload__file-status {
		background-color: rgba(0, 0, 0, 0.6) !important;
	}

	::v-deep .u-upload__delete {
		background-color: rgba(239, 68, 68, 0.8) !important;
		border-radius: 50% !important;
		width: 24px !important;
		height: 24px !important;
		line-height: 24px !important;
	}
</style>